package com.example.star.view.setting;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.star.R;
import com.example.star.adapter.ReplyAdapter;
import com.example.star.api_service.ApiFeedback;
import com.example.star.entity.Feedback;
import com.example.star.entity.Reply;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SendFeedbackActivity extends AppCompatActivity {

    private EditText feedbackEditText;
    private Button sendFeedbackButton;
    private ListView replyListView;
    private Spinner adminUserSpinner;
    private TextView currentUserNameTextView; // 用于显示当前用户名的 TextView
    private String currentUserName;
    private String selectedAdminName;
    private ReplyAdapter replyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_feedback);

        // 从 SharedPreferences 读取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        currentUserName = sharedPreferences.getString("username", "");

        initViews();

        // 设置当前用户名到 TextView（如果有对应的 TextView）
        currentUserNameTextView.setText(currentUserName);

        getAdminUsers();
        getReplies();

        sendFeedbackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendFeedback();
            }
        });
    }

    private void initViews() {
        feedbackEditText = findViewById(R.id.et_feedback);
        sendFeedbackButton = findViewById(R.id.btn_send_feedback);
        replyListView = findViewById(R.id.lv_replies);
        adminUserSpinner = findViewById(R.id.admin_user_spinner);
        // 初始化用于显示当前用户名的 TextView（如果有对应的布局控件）
        currentUserNameTextView = findViewById(R.id.current_user_name_text_view);
    }

    private void getAdminUsers() {
        ApiFeedback apiFeedback = ApiClient.getApiFeedback();
        Call<List<User>> call = apiFeedback.getAdminUsers();
        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if (response.isSuccessful()) {
                    List<User> adminUsers = response.body();
                    if (adminUsers != null) {
                        List<String> usernames = new ArrayList<>();
                        for (User user : adminUsers) {
                            usernames.add(user.getUsername());
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(SendFeedbackActivity.this,
                                android.R.layout.simple_spinner_item, usernames);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        adminUserSpinner.setAdapter(adapter);

                        adminUserSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                selectedAdminName = (String) parent.getItemAtPosition(position);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                            }
                        });
                        Toast.makeText(SendFeedbackActivity.this, "获取管理员用户成功", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e("User", "获取管理员用户失败: " + response.message());
                    Toast.makeText(SendFeedbackActivity.this, "获取管理员用户失败: " + response.message(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                Log.e("User", "网络请求失败: " + t.getMessage() + ", 请求接口: getAdminUsers");
                Toast.makeText(SendFeedbackActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void sendFeedback() {
        String feedbackText = feedbackEditText.getText().toString();
        if (feedbackText.isEmpty()) {
            Toast.makeText(this, "请输入消息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (selectedAdminName == null || selectedAdminName.isEmpty()) {
            Toast.makeText(this, "请选择管理员", Toast.LENGTH_SHORT).show();
            return;
        }


        // 创建消息对象
        Feedback feedback = new Feedback();
        feedback.setUserName(currentUserName);
        feedback.setAdminName(selectedAdminName);


        // 这里需要根据实际情况创建 User 对象并设置到 Reply 中
        User user = new User();
        user.setUsername(selectedAdminName);
        feedback.setUser(user);
        feedback.setMessage(feedbackText);

        ApiFeedback apiFeedback = ApiClient.getApiFeedback();
        Call<Void> call = apiFeedback.createFeedback(feedback);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.d("Feedback", "反馈发送成功");
                    feedbackEditText.setText("");
                    getReplies();
                    Toast.makeText(SendFeedbackActivity.this, "反馈发送成功", Toast.LENGTH_SHORT).show();
                } else {
                    Log.e("Feedback", "反馈发送失败: " + response.message());
                    Toast.makeText(SendFeedbackActivity.this, "反馈发送失败: " + response.message(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e("Feedback", "网络请求失败: " + t.getMessage() + ", 请求接口: createFeedback");
                Toast.makeText(SendFeedbackActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getReplies() {
        ApiFeedback apiFeedback = ApiClient.getApiFeedback();
        Call<List<Reply>> call = apiFeedback.getRepliesByUserName(currentUserName);
        call.enqueue(new Callback<List<Reply>>() {
            @Override
            public void onResponse(Call<List<Reply>> call, Response<List<Reply>> response) {
                if (response.isSuccessful()) {
                    List<Reply> replies = response.body();
                    if (replies != null) {
                        for (Reply reply : replies) {
                            Log.d("Reply", "Admin Name: " + reply.getAdminName());
                        }
                    }
                    replyAdapter = new ReplyAdapter(SendFeedbackActivity.this, replies);
                    replyListView.setAdapter(replyAdapter);
                    Toast.makeText(SendFeedbackActivity.this, "获取回复列表成功", Toast.LENGTH_SHORT).show();
                } else {
                    Log.e("Reply", "获取回复列表失败: " + response.message());
                    Toast.makeText(SendFeedbackActivity.this, "获取回复列表失败: " + response.message(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<Reply>> call, Throwable t) {
                Log.e("Reply", "网络请求失败: " + t.getMessage() + ", 请求接口: getRepliesByUserName");
                Toast.makeText(SendFeedbackActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }


}